/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.date.DateTime;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.app.utils.QCodeService;
import io.renren.modules.user.entity.UserEntity;
import io.renren.modules.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.protocol.HttpContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private QCodeService qCodeService;
    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form) {

        String code = form.getCode();
        if (code == null) {
            return R.error();
        }

        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            return R.error();
        }
        UserEntity user = userService.queryByOpenId(openId);
        if (user == null) {
            user = new UserEntity();
            user.setUsername(openId);
            user.setOpenId(openId);
            user.setSessionKey(sessionKey);
            user.setModifyTime(DateTime.now());
            user.setCreateTime(DateTime.now());
            user.setLastTime(DateTime.now());
            user.setDeleted(0);
            user.setIp(IPUtils.getIpAddr(httpServletRequest));
            user.setInviteUserId(form.getInviteUserId());
            userService.save(user);
        } else {
            user.setIp(IPUtils.getIpAddr(httpServletRequest));
            user.setLastTime(DateTime.now());
            user.setSessionKey(sessionKey);
            if (!userService.updateById(user)) {
                return R.error();
            }
        }
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", user);
        result.put("expire", jwtUtils.getExpire());

        return R.ok(result);
    }


    @GetMapping("getShareImage")
    @Login
    public R getShareImage(@RequestAttribute("userId") Long userId) {

        String shareImage = qCodeService.createGoodShareImage(userId);

        return R.ok(shareImage);
    }
}
